import { Request, Response } from 'express';
import { z } from 'zod';

import { ProjectModel } from '../../models/project';
import { sendErrorResponse, sendSuccessResponse } from '../../utils/response';

/**
 * 查询项目列表的查询参数验证模式
 */
export const listProjectsSchema = z.object({
  // 每页数量，默认为10，最大100
  limit: z
    .string()
    .optional()
    .transform(val => (val ? parseInt(val, 10) : 10))
    .refine(val => val > 0 && val <= 100, '每页数量必须在1-100之间'),
  // 项目名称模糊查询
  name: z
    .string()
    .optional()
    .transform(val => val?.trim()),
  // 页码，默认为1
  page: z
    .string()
    .optional()
    .transform(val => (val ? parseInt(val, 10) : 1))
    .refine(val => val > 0, '页码必须大于0'),
});

export type ListProjectsQuery = z.infer<typeof listProjectsSchema>;

/**
 * 项目列表响应数据结构
 */
export interface ListProjectsResponse {
  projects: any[];
  total: number;
}

/**
 * 获取项目列表接口
 * @description 支持分页和项目名称模糊查询
 * @route GET /api/project
 * @param req Express请求对象
 * @param res Express响应对象
 * @returns Promise<Response> 项目列表响应
 *
 * @example
 * GET /api/project?page=1&limit=10&name=示例
 *
 * 成功响应:
 * {
 *   "success": true,
 *   "code": 200,
 *   "message": "获取项目列表成功",
 *   "data": {
 *     "projects": [
 *       {
 *         "_id": "507f1f77bcf86cd799439011",
 *         "name": "示例项目",
 *         "apps": ["507f1f77bcf86cd799439012"],
 *         "remark": "这是一个示例项目",
 *         "scripts": [],
 *         "createdAt": "2024-01-01T00:00:00.000Z",
 *         "updatedAt": "2024-01-01T00:00:00.000Z"
 *       }
 *     ],
 *     "pagination": {
 *       "currentPage": 1,
 *       "totalPages": 5,
 *       "totalItems": 50,
 *       "itemsPerPage": 10
 *     }
 *   }
 * }
 */
export async function listProjects(req: Request, res: Response): Promise<Response> {
  try {
    const { limit, name, page } = req.query as unknown as ListProjectsQuery;

    // 构建查询条件
    const query: any = {};

    // 如果提供了名称参数且不为空，则进行模糊查询
    if (name && name.length > 0) {
      query.name = { $options: 'i', $regex: name };
    }

    // 计算跳过的文档数量
    const skip = (page - 1) * limit;

    // 并行执行查询和计数操作以提高性能
    const [projects, totalItems] = await Promise.all([
      ProjectModel.find(query)
        .populate('apps', 'name type url') // 填充关联的应用信息
        .sort({ createdAt: -1 }) // 按创建时间倒序排列
        .skip(skip)
        .limit(limit)
        .lean(), // 使用lean()提高查询性能
      ProjectModel.countDocuments(query),
    ]);

    const responseData: ListProjectsResponse = {
      projects,
      total: totalItems,
    };

    return sendSuccessResponse(res, responseData, '获取项目列表成功');
  } catch (error) {
    console.error('获取项目列表失败:', error);

    // 处理MongoDB相关错误
    if (error instanceof Error) {
      if (error.name === 'CastError') {
        return sendErrorResponse(res, 400, '查询参数格式不正确');
      }
    }

    return sendErrorResponse(res, 500, '服务器内部错误');
  }
}
